<?php

namespace app\controllers\h5\uni;

use app\controllers\h5\base\H5Controller;
use app\models\system\SetSwiper;
use app\redis\Cache;
use app\models\product\ProductCategory as Model;
use app\controllers\h5\services\Category as Service;

/**
 * Class CategoryController
 * @package app\controllers\h5\uni
 */
class CategoryController extends H5Controller
{
    public function actionIndex()
    {
        $cache = Cache::get(Cache::$PAGE_CATEGORY);

        if (!$cache || true) {
            $data = [
                'swiper' => $this->swiper(),
                'firstLevel' => $this->firstLevelCategory(),
            ];

            // first children list (2 & 3 level children list)
            if ($data['firstLevel'] && count($data['firstLevel']) > 0) {
                $data['firstChildren'] = $this->firstChildren($data['firstLevel'][0]['id']);
            }

            Cache::set(Cache::$PAGE_CATEGORY, json_encode($data));
        } else {
            $data = json_decode($cache, true);
        }

        // var_dump($data);exit;

        return $this->successEncode($data);
    }

    private function swiper()
    {
        $list = SetSwiper::find()
            ->where(['status' => SetSwiper::$statusMapping['OK']])
            ->andWhere(['category_id' => 3])
            ->orderBy(['sort' => SORT_ASC, 'id' => SORT_DESC])
            ->with(['image'])
            // ->select(['id', 'image_id'])
            ->asArray()
            ->all();

        // 图片缓存
        foreach ($list as &$item) {
            if ($item['image']) {
                if ($item['image']['path']) {
                    $item['image']['path'] .= '?=' . time() . mt_rand(100000, 999999);
                }
                if ($item['image']['thumbnail_path']) {
                    $item['image']['thumbnail_path'] .= '?=' . time() . mt_rand(100000, 999999);
                }
            }
        }

        return $list;
    }

    // left menu list
    private function firstLevelCategory()
    {
        // return Model::getCategoriesByParent();

        $list = Model::find()
            ->where(['status' => 1])
            ->orderBy(['sort' => SORT_ASC, 'id' => SORT_DESC])
            ->asArray()
            ->all();

        return $list;
    }

    // default first children list
    private function firstChildren($parent_id)
    {
        return Service::getChildrenByParent($parent_id);
    }
}